<?php

namespace common\components\form\field;

use Yii;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use common\components\form\Form;
use common\components\form\Field;

/**
 * description of Unknown
 *
 * @author FireLoong
 */
class Unknown extends Field
{
    public function setup($options = ['class' => 'form-control'])
    {
        if ($this->setupParams) {
            $options = $this->setupParams[0] ?? $options;
        }

        $options = array_merge($this->inputOptions, $options);
        if ($this->form->validationStateOn === Form::VALIDATION_STATE_ON_INPUT) {
            $this->addErrorClassIfNeeded($options);
        }

        $this->addAriaAttributes($options);
        $this->adjustLabelFor($options);
        $this->parts['{input}'] = Html::activeInput($this->type, $this->model, $this->attribute, $options);

        return $this;
    }

    public function xmlSetup(\SimpleXMLElement $field, $options = [])
    {
        $data = ArrayHelper::remove($options, 'data');

        $options = array_merge($this->inputOptions, $options);

        if ($this->form->validationStateOn === Form::VALIDATION_STATE_ON_INPUT) {
            $this->addErrorClassIfNeeded($options);
        }

        $this->addAriaAttributes($options);
        $this->adjustLabelFor($options);

        $options['value'] = (string)$field->attributes()->default;

        //var_dump($this->model->{$this->attribute});

        $this->attribute = $this->attribute . '[' . (string)$field->attributes()->name . ']';

        $this->parts['{input}'] = Html::activeInput($this->type, $this->model, $this->attribute, $options);

        return $this->label(Yii::t($data['langCat'], (string)$field->attributes()->label));
    }

    public function xSetup(\SimpleXMLElement $field, $options = [])
    {
        $inputOptions = array_merge($this->inputOptions, ArrayHelper::remove($options, 'inputOptions') ?? []);
        $data = ArrayHelper::remove($options, 'data');

        $attribute = substr($this->attribute, 0, -strlen('[' . (string)$field->attributes()->name . ']'));

        $attributeArray = json_decode($this->model->$attribute, true);
        if (is_null($attributeArray) || !isset($attributeArray[(string)$field->attributes()->name])) {
            $inputOptions['value'] = (string)$field->attributes()->default;
        }else{
            $inputOptions['value'] = $attributeArray[(string)$field->attributes()->name];
        }

        $this->parts['{input}'] = Html::activeInput($this->type, $this->model, $this->attribute, $inputOptions);

        $label = Yii::t($data['langCat'], (string)$field->attributes()->label);

        $description = (string)$field->attributes()->description;
        $labelOptions = [];
        if (!empty($description)) {
            $labelOptions['desc'] = Yii::t($data['langCat'], $description);
        }

        return $this->label($label, $labelOptions);
    }
}
